<?php

namespace app\admin\controller;

use app\admin\library\Auth;
use app\common\controller\Backend;
use think\Db;
use think\Session;
/**
 * 開懷圈申請審核
 *
 * @icon fa fa-circle-o
 */
class VolunteerAudit extends Backend
{

    /**
     * VolunteerAudit模型对象
     * @var \app\admin\model\VolunteerAudit
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\VolunteerAudit;
        $this->view->assign("statusList", $this->model->getStatusList());
    }

    public function import()
    {
        parent::import();
    }

    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        $auth                         = Auth::instance();
        $auth_affiliated_center_id    = db('admin')->where('id', $auth->id)->value('affiliated_center_id');
        $auth_affiliated_center_arr   = db('area')->where('pid',0)->column('id');
        $auth_affiliated_center_arr[] = 0;
        if ($auth_affiliated_center_id > 0) {
            $auth_affiliated_center_arr = explode(',',$auth_affiliated_center_id);
        }
        
        //当前是否为关联查询
        $this->relationSearch = true;
        //设置过滤方法
        $this->request->filter(['strip_tags', 'trim']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            if ($this->request->request('keyField')) {
                return $this->selectpage();
            }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();



            $admin = Session::get('admin');
            $where2=[];
            if ($admin['affiliated_center_id'] !=0) {
                $arr_area = explode(',', $admin['affiliated_center_id']);

                $where2['affiliated_center_id'] = ['in', $arr_area];

            }

            $list = $this->model
                ->with(['user'])
                ->where($where)
                ->where($where2)
              
                ->order($sort, $order)
                ->paginate($limit);
            foreach ($list as $row) {

                $row->getRelation('user')->visible(['nickname', 'avatar']);

                $row['id_card_hk'] = $row['id_card_front'].$row['id_card'] . '(' . $row['id_card_after'] . ')';

                // $region_address = db('region')->where(['id' => $row->province])->value('name');
                // $city           = db('region')->where(['id' => $row->city])->value('name');
                // if ($city) {
                //     $region_address = $region_address . $city;
                //     $district       = db('region')->where(['id' => $row->district])->value('name');
                //     if ($district) {
                //         $region_address = $region_address . $district;
                //     }
                // }
                // $row->region_address = $region_address ? $region_address : '';
            }

            $result = array("total" => $list->total(), "rows" => $list->items());

            return json($result);
        }
        $this->assignconfig("volunteer_audit_edit", $this->auth->check("volunteer_audit/edit"));
        $this->assignconfig("volunteer_audit", $this->auth->check("volunteer_audit/audit"));
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $province = db('region')->field('id as value, name')->where(['id' => $row['province']])->find();
        $city     = db('region')->field('id as value, name')->where(['id' => $row['city']])->find();
        $district = db('region')->field('id as value, name')->where(['id' => $row['district']])->find();
        $this->view->assign("province", $province);
        $this->view->assign("city", $city);
        $this->view->assign("district", $district);

        $area_one_id = db('area')->field('id as value, name')->where(['id' => $row['area_one_id']])->find();
        $area_tow_id = db('area')->field('id as value, name')->where(['id' => $row['area_tow_id']])->find();

        $this->view->assign("area_one_id", $area_one_id);
        $this->view->assign("area_tow_id", $area_tow_id);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params             = $this->preExcludeFields($params);
                $result             = false;
                $params['province'] = input('province', 0);
                $params['city']     = input('city', 0);
                $params['district'] = input('district', 0);

                $params['area_one_id'] = input('area_one_id', 0);
                $params['area_tow_id'] = input('area_tow_id', 0);
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $result = $row->allowField(true)->save($params);
                    // 通過，加人
                    if ($params['status'] == 2) {
                        $count = db('volunteer')->where('affiliated_center_id',$row['affiliated_center_id'])->where(['user_id' => $row['user_id'], 'deletetime' => null])->count();
                        if ($count==0) {
                            $insert_arr                            = [];
                            $insert_arr['user_id']                 = $row['user_id'];
                            $insert_arr['name']                    = $row['name'];
                            $insert_arr['mobile']                  = $row['mobile'];
                            $insert_arr['province']                = $row['province'];
                            $insert_arr['city']                    = $row['city'];
                            $insert_arr['district']                = $row['district'];
                            $insert_arr['address']                 = $row['address'];
                            $insert_arr['createtime']              = time();
                            $insert_arr['volunteer_audit_id']      = $row['id'];
                            $insert_arr['id_card']                 = $row['id_card'];
                            $insert_arr['id_card_front']           = $row['id_card_front'];
                            $insert_arr['id_card_after']           = $row['id_card_after'];
                            $insert_arr['id_card_positive_images'] = $row['id_card_positive_images'];
                            $insert_arr['id_card_back_images']     = $row['id_card_back_images'];
                            $insert_arr['birthday']                = $row['birthday'];
                            $insert_arr['email']                   = $row['email'];

                            $insert_arr['area_one_id']          = $row['area_one_id'];
                            $insert_arr['area_tow_id']          = $row['area_tow_id'];
                            $insert_arr['affiliated_center_id'] = $row['affiliated_center_id'];
                            $insert_arr['wechat_id'] = $row['wechat_id'];
                            $insert_arr['mobile_china'] = $row['mobile_china'];
                            $insert_arr['remark'] = $row['remark'];
                            $insert_arr['service_type'] = $row['service_type'];
                         
                            db('volunteer')->insertGetId($insert_arr);
                        }
                        sendMessage(1, '您的義工申請已通過', '', $row['user_id'], 5, -6);
                    } else {
                        sendMessage(1, '您的義工申請未能通過，點擊查看詳細原因', '', $row['user_id'], 5, -6);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

    /**
     * 编辑
     */
    public function audit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        if ($row['status'] !== '1') {
            $this->error('狀態錯誤');
        }
        $province = db('region')->field('id as value, name')->where(['id' => $row['province']])->find();
        $city     = db('region')->field('id as value, name')->where(['id' => $row['city']])->find();
        $district = db('region')->field('id as value, name')->where(['id' => $row['district']])->find();

        $area_one_id = db('area')->field('id as value, name')->where(['id' => $row['area_one_id']])->find();
        $area_tow_id = db('area')->field('id as value, name')->where(['id' => $row['area_tow_id']])->find();
        $this->view->assign("province", $province);
        $this->view->assign("city", $city);
        $this->view->assign("district", $district);

        $this->view->assign("area_one_id", $area_one_id);
        $this->view->assign("area_tow_id", $area_tow_id);
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params['status'] == '3' && !$params['audreason']) {
                $this->error('請填寫拒絕原因');
            }
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    $params['audittime'] = time();
                    $result              = $row->allowField(true)->save($params);
                    // 通過，加人
                    if ($params['status'] == 2) {
                        $count = db('volunteer')
                        ->where('affiliated_center_id',$row['affiliated_center_id'])
                        ->where('area_tow_id',$row['area_tow_id'])
                        ->where(['user_id' => $row['user_id'], 'deletetime' => null])->count();
                        if ($count==0) {
                            $insert_arr                            = [];
                            $insert_arr['user_id']                 = $row['user_id'];
                            $insert_arr['name']                    = $row['name'];
                            $insert_arr['mobile']                  = $row['mobile'];
                            $insert_arr['province']                = $row['province'];
                            $insert_arr['city']                    = $row['city'];
                            $insert_arr['district']                = $row['district'];
                            $insert_arr['address']                 = $row['address'];
                            $insert_arr['createtime']              = time();
                            $insert_arr['volunteer_audit_id']      = $row['id'];
                            $insert_arr['id_card']                 = $row['id_card'];
                            $insert_arr['id_card_front']           = $row['id_card_front'];
                            $insert_arr['id_card_after']           = $row['id_card_after'];
                            $insert_arr['id_card_positive_images'] = $row['id_card_positive_images'];
                            $insert_arr['id_card_back_images']     = $row['id_card_back_images'];
                            $insert_arr['birthday']                = $row['birthday'];
                            $insert_arr['email']                   = $row['email'];

                            $insert_arr['area_one_id'] = $row['area_one_id'];
                            $insert_arr['area_tow_id'] = $row['area_tow_id'];
                            $insert_arr['affiliated_center_id'] = $row['affiliated_center_id'];
                               $insert_arr['wechat_id'] = $row['wechat_id'];
                            $insert_arr['mobile_china'] = $row['mobile_china'];
                            $insert_arr['remark'] = $row['remark'];
                            $insert_arr['service_type'] = $row['service_type'];

                            db('volunteer')->insertGetId($insert_arr);
                        }
                        sendMessage(1, '您的義工申請已通過', '', $row['user_id'], 5, -6);
                    } else {
                        sendMessage(1, '您的義工申請未能通過，點擊查看詳細原因', '', $row['user_id'], 5, -6);
                    }
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $this->view->assign("row", $row);
        return $this->view->fetch();
    }

}
